//
// Created by ziya on 2021/1/17.
//

#ifndef STACK_ENGINE_STACK_H
#define STACK_ENGINE_STACK_H

#include <stdio.h>
#include <stdlib.h>

template<typename T>
class Stack {

private:
    T* _data;

    int _top;
    int _maxSize;

public:
    Stack(int size) {
        _top = 0;
        _maxSize = size;

        _data = new T[size];
    }

    ~Stack() {
        delete _data;
    }

public:
    int size() {
        return _top;
    }

public:
    void push(T val) {
        if (_top > _maxSize - 1) {
            printf("栈越界\n");

            exit(-1);
        }

        _data[_top++] = val;

        // 调整栈顶
        if (_top >= _maxSize) _top = _maxSize - 1;
    }

    void pop() {
        if (_top < 0) {
            printf("栈已到底\n");

            exit(-1);
        }

        _top -= 1;

        if (_top < 0) _top = 0;
    }

    T popData() {
        if (_top < 0) {
            printf("栈已到底\n");

            exit(-1);
        }

        T r = _data[_top--];

        if (_top < 0) _top = 0;

        return r;
    }

    T top() {
        return _data[_top - 1];
    }

#ifdef DEBUG
public:
    void print(const char *str) {
        printf("%s: top=%d, max=%d\n", str, _top, _maxSize);
    };
#endif

};


#endif //STACK_ENGINE_STACK_H
